//===========================================================================
// This file was modified as part of an ASP.NET 2.0 Web project conversion.
// The class name was changed and the class modified to inherit from the abstract base class 
// in file 'App_Code\Migrated\personnel\Stub_labordistribution_aspx_cs.cs'.
// During runtime, this allows other classes in your web application to bind and access 
// the code-behind page using the abstract base class.
// The associated content page 'personnel\labordistribution.aspx' was also modified to refer to the new class name.
// For more information on this code pattern, please refer to http://go.microsoft.com/fwlink/?LinkId=46995 
//===========================================================================

using System;
using System.Collections;
using System.Text;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.InsightWebControls;
using PHSRAG.Insight21.Personnel;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Utility;
using Constants=PHSRAG.Insight21.InsightUtilities.Constants;
using Distribution = PHSRAG.Insight21.Personnel.LaborDistribution;
using PersonnelConstants = PHSRAG.Insight21.Personnel.Constants;
using SPROCArgsIndex = PHSRAG.Insight21.Personnel.LaborDistributionArgumentIndex;

namespace PHSRAG.Insight21
{
    /// <summary>
    /// The LaborDistribution class supports the LaborDistribution.aspx page.
    /// It displays the distribution for the personnel within the given set of criteria
    /// depending on the module/page from which this page is requested.
    /// The user can navigate to this page either from the Personnel Sub-module navigation or 
    /// from the Salaries Overview or Budget Overview or Expense Overview in the agreements module
    /// </summary>
    /// <remarks>
    /// The LaborDistribution page supports searching/filtering the distribution data
    /// based on user-defined and user-selectable search criteria.
    /// Following is the list of such criteria:
    /// <list type="bullet">
    /// <item><description>Employee Last Name (free-form entry)</description></item>
    /// <item><description>Employee First Name (free-form entry)</description></item>
    /// <item><description>Effective Pay Date From/To (select both from a calender control)</description></item>
    /// </list>
    /// </remarks>
    public partial class LaborDistribution : NoCachePage
    {
        #region Constants

        private const string CurrentPageIndexKey = "CurrentPageIndex_5B40975C-13DE-4161-AF82-5A5119C877DB";
        private const string DeficitStyleName = "deficit";
        private const string TotalsColumnName = "TotalAmount";
        private const int TotalsRowIndex = 0;

        #endregion

        #region Enums (Private)

        #region Nested type: DataGridColumnIndex

        private enum DataGridColumnIndex
        {
            Name,
            FundNumber,
            EarningsCode,
            JobCode,
            PayDate,
            RetroPayAdjustmentDate,
            PayAmount
        }

        #endregion

      

        #endregion

        #region Instance variables (Private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;
        //private double totalGL;
        private double totalLabor;

        #endregion

        #region Private Properties

        /// <summary>
        /// Get the labor distribution informations that the logged-in user has access to. The list of distributions is
        /// is maintained by the LabourDistributions business object within its data container. This object is cached.
        /// The LaborDistributions instance is loaded based on from where the user is navigating to this page.
        /// Everytime the page is loaded for the firsttime the LaborDistributions instance will be reloaded.
        /// </summary>
        private LaborDistributions LaborDistributionsInstance
        {
            get
            {
                LaborDistributions laborDistributions =
                    ResultsCache.GetObject(cachePolicy, LaborDistributions.CacheKey) as LaborDistributions;

                if (laborDistributions == null)
                {
                    UserContext userContext = (UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey);

                    laborDistributions = new LaborDistributions();
                    Hashtable dictionary = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;

                    if (dictionary == null ||
                        dictionary[Constants.PageNameKey] == null ||
                            (string) dictionary[Constants.PageNameKey] == string.Empty)
                    {
                        dictionary = (Hashtable) pageCachePolicy.GetCachedObject("LaborDistributionDetailsKey");
                    }
                   
                    string fundNumber;
                    string selectedBudgetDetailFundNumber = dictionary[Keys.SelectedBudgetDetailFundNumberKey] as String;
                    if (!string.IsNullOrEmpty(selectedBudgetDetailFundNumber))
                    {
                        //we came in from the budget details page and a fund was selected so use that one
                        //remove from the dictionary, and recache the dictionary.
                        fundNumber = selectedBudgetDetailFundNumber;
                    }
                    else
                    {
                        fundNumber = (string) dictionary[Keys.FundNumberKey] ?? (string) dictionary[Constants.FundNumberKey];
                    }

                    laborDistributions.Load(DataAccess.ConnectionString, Session.SessionID
                        , ((CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString())
                        , dictionary, fundNumber, DictionaryCumulativeFlag);

                    totalLabor = laborDistributions.TotalLabor;
                  
                    pageCachePolicy.UnCache(Keys.IncomingDataKey);

                    ResultsCache.SetObject(cachePolicy, LaborDistributions.CacheKey, laborDistributions);
                }

                return laborDistributions;
            }
        }

        /// <summary>
        /// Get/Set the current page within the datagrid for display. This information persists across page loads.
        /// This information is cached using the page cache policy
        /// Get: Return the value from the page cache policy, returns 0 if its not present in cache
        /// Set: Set the value and update the cache
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.LaborDistributionPageKey) as Hashtable;
                return (h == null || h[CurrentPageIndexKey] == null) ? 0 : (int) h[CurrentPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.LaborDistributionPageKey) as Hashtable ?? new Hashtable();
                h[CurrentPageIndexKey] = value;
                laborDistributionGrid.CurrentPageIndex = value;
                pageCachePolicy.Cache(Keys.LaborDistributionPageKey, h);
            }
        }


        /// <summary>
        /// Get/Set the Cumulative flag (it was originated on the BudgetDetai page).
        /// </summary>
        private int DictionaryCumulativeFlag
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.LaborDistributionPageKey) as Hashtable;
                if (h == null)
                {
                    return 0;
                }
                object dictionaryCumulativeFlag = h[Keys.CumulativeKey];
                return (dictionaryCumulativeFlag == null) ? 0 : (int) dictionaryCumulativeFlag;
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.LaborDistributionPageKey) as Hashtable ?? new Hashtable();
                h[Keys.CumulativeKey] = value;
                laborDistributionGrid.CurrentPageIndex = value;
                pageCachePolicy.Cache(Keys.LaborDistributionPageKey, h);
            }
        }

        #endregion

        # region Event Handlers

        #region Page load

        /// <summary>
        /// Handler for the event raised when the page is being loaded.
        /// Initialize the bread crumb control, set the page size for the data grid, and load the data grid with data.
        /// If on the first page within the data grid, initalize the pager control.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                //reportDownload.SQLReportName = "labordistribution";
                annunciator.Message = string.Empty;
                annunciator.Title = string.Empty;

                breadCrumb.Add(
                    "Labor Distribution",
                    Settings.GetKeyValue("SubNavigation.Personnel.LaborDistributionURL", string.Empty),
                    (insightHeader.ModuleName == Constants.Modules.Agreements)
                        ? Settings.GetKeyValue("BreadCrumb.SubDetailPageLevel", 3)
                        : Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));

                agreementsSubNavigation.Visible = false;
                if (insightHeader.ModuleName == Constants.Modules.Agreements)
                {
                    Hashtable h = (Hashtable) cachePolicy.GetCachedObject(Constants.AgreementsConstants.AgreementDetailsKey);
                    if (h == null)
                    {
                        agreementsSubNavigation.Visible = true;
                        agreementDetailsSubNavigation.Visible = false;
                        agreementsSubNavigation.EnableOverviewNavigation = true;
                        personnelSubNavigation.Visible = false;
                    }
                    else
                    {
                        agreementsSubNavigation.Visible = true;
                        agreementDetailsSubNavigation.Visible = true;
                        agreementsSubNavigation.EnableOverviewNavigation = false;
                        personnelSubNavigation.Visible = false;
                    }
                   
                }
                else
                {
                    personnelSubNavigation.Visible = true;
                    agreementsSubNavigation.Visible = false;
                    agreementDetailsSubNavigation.Visible = false;
                }

                if (IsPostBack)
                {
                    ManagePagination();
                }
                else
                {
                    ResultsCache.PurgeObject(cachePolicy);

                    laborDistributionGrid.PageSize =
                        Settings.GetKeyValue(PersonnelConstants.DataGridPageSizeKey
                            , PersonnelConstants.DefaultDatagridPageSize);


                    Hashtable dictionary = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                    Hashtable agreemnetDetails = cachePolicy.GetCachedObject(Constants.AgreementsConstants.AgreementDetailsKey) as Hashtable;

                    string referringPage = string.Empty;
                    if (dictionary != null)
                    {
                        referringPage = (dictionary[Constants.PageNameKey] == null) ? string.Empty : dictionary[Constants.PageNameKey].ToString();
                        //TrackIt 7995 - 03/11/2008 jml29
                        DictionaryCumulativeFlag = (dictionary[Keys.CumulativeKey] == null) ? 0 : Convert.ToInt32(dictionary[Keys.CumulativeKey].ToString());
                    }


                    //if we arrived here via the Agreements Module it is mandatory that we had set the value of 
                    //the referring page key in the cached hash table.
                    if (referringPage != string.Empty)
                    {
                        insightHeader.ModuleName = Constants.Modules.Agreements;
                        personnelSubNavigation.Visible = false;
                        if ((referringPage == "Budget" || referringPage == "Expense" || referringPage == "Salaries") &&
                            agreemnetDetails == null)
                        {
                            agreementsSubNavigation.Visible = true;
                            agreementDetailsSubNavigation.Visible = false;
                            agreementsSubNavigation.EnableOverviewNavigation = true;
                        }
                        else
                        {
                            // referringPage is "BudgetDetails"
                            agreementsSubNavigation.Visible = true;
                            agreementsSubNavigation.EnableOverviewNavigation = false;
                            agreementDetailsSubNavigation.Visible = true;
                        }
                        
                    }
                    else
                    {
                        //we came from personnel b/c no entry for referring page in cache.
                        insightHeader.ModuleName = Constants.Modules.Personnel;
                        personnelSubNavigation.SelectedLink = PersonnelSubNavigation.laborDistributionCommand;
                        agreementsSubNavigation.Visible = false;
                        agreementDetailsSubNavigation.Visible = false;
                    }

                    ProcessSearch();
                    reportDownload.SQLReportName = "labordistribution";
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        #endregion

        #region Datagrid event handlers

        /// <summary>
        /// Handler for event raised while each data grid item is created.
        /// Help in putting the symbol denoting the sort column in the data grid.
        /// If the item being created is the data grid header:
        /// <list type="bullet">
        /// <item><description>Get the sort column and sort order from the LaborDistributions instance in the cache</description></item>
        /// <item><description>Create a Hashtable of column indices, keyed by the sort expression of each column</description></item>
        /// <item><description>Using the hash table add a label with sort symbol to the column on which sort has happened</description></item>
        /// </list>
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    LaborDistributions laborDistribs = LaborDistributionsInstance;
                    Label sortSymbol = new Label();
                    sortSymbol.Text = laborDistribs.SortAscending ? Constants.SortAscendingText : Constants.SortDescendingText;
                    sortSymbol.Font.Name = Constants.SortSymbolFontName;

                    Hashtable columnMap = new Hashtable();
                    foreach (DataGridColumn column in laborDistributionGrid.Columns)
                    {
                        columnMap[column.SortExpression] = laborDistributionGrid.Columns.IndexOf(column);
                    }

                    string sortColumn = laborDistribs.SortColumn;
                    if (columnMap.ContainsKey(sortColumn))
                    {
                        e.Item.Cells[(int) columnMap[sortColumn]].Controls.Add(sortSymbol);
                    }
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// Handler for the event raised when a column header within the data grid is clicked.
        /// Set the currentpageindex to 0 as sorting need to be done on all records and not only on what is visible
        /// Load the data grid and intialize the pager controls
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnSort(object sender, DataGridSortCommandEventArgs e)
        {
            try
            {
                if (e.SortExpression != string.Empty)
                {
                    LaborDistributionsInstance.Sort(e.SortExpression);
                    CurrentPageIndex = 0;
                    LoadDataGrid();
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// Handler for the event raised when a row in the datagrid is databound.
        /// Bind the cells in the Footer with the totals.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                DataGridItem distribItem = e.Item;

                if (distribItem.ItemType == ListItemType.Item || distribItem.ItemType == ListItemType.AlternatingItem)
                {
                    TableCell payAmountCell = distribItem.Cells[(int) DataGridColumnIndex.PayAmount];
                    decimal payAmount = Convert.ToDecimal(payAmountCell.Text);
                    if (payAmount < 0)
                    {
                        payAmountCell.CssClass = DeficitStyleName;
                    }
                    payAmountCell.Text = payAmount.ToString("c");
                }
                else if (distribItem.ItemType == ListItemType.Footer)
                {
                    e.Item.Cells[(int) DataGridColumnIndex.Name].Text = "Total";

                    distribItem.Cells[(int) DataGridColumnIndex.PayAmount].Text =
                        string.Format("{0:c}", LaborDistributionsInstance.GetDataContainer().
                            Tables[LaborDistributionsInstance.CurrentDataTableName].
                            Compute("sum(payamount)", string.Empty));
                }
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

       

       
        #endregion

        #region Paging event handlers

        /// <summary>
        /// Handler for the event raised when the FirstPage link is clicked in the Pager control.
        /// Set the current page index to 0, bind the datagrid with data and manage navigation links.
        /// To avoid superfluous data binding activites, no action is taken if the current page index is already 0.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnFirstPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

      
        /// <summary>
        /// Handler for the event raised when the LastPage link is clicked in the Pager control.
        /// Set the current page index to one less than the total page count (index is 0-based), bind the datagrid with
        /// data and manage navigation links.
        /// To avoid superfluous data binding activites, no action is taken if the current 
        /// page index is already corresponding to the last page.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnLastPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = pagerAboveDatagrid.PageCount - 1;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

      
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            if (((CommandEventArgs) (e.CommandArgument)).CommandName == Convert.ToString((int) SearchCriteria.Level.Summary))
            {
                //set the search context's level to the correct level
                CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                searchContext.CurrentLevel = SearchCriteria.Level.Summary;
            }
        }

        /// <summary>
        /// Handler for the event raised when the NextPage link is clicked in the Pager control.
        /// Increment the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnNextPage(object sender, CommandEventArgs e)
        {
            try
            {
                ++CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

     

        /// <summary>
        /// Handler for the event raised when the PreviousPage link is clicked in the Pager control.
        /// Decrement the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnPreviousPage(object sender, CommandEventArgs e)
        {
            try
            {
                --CurrentPageIndex;
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

      
        #endregion

        #region Header

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                personnelSubNavigation.Reset();
                PurgeCache();
            }
            catch (Exception ex)
            {
                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        #endregion

        #endregion

        #region Private Methods

        /// <summary>
        /// Load the datagrid with sufficient data for display within one page of the data grid. This is done as follows:
        /// Get the distribution for all personnel that the user has access to. Use that to initialize the data grid and
        /// the pager controls based on the page size of the data grid.
        /// The pagers are made visible only when more than one page of data can be displayed.
        /// If there is no data to display, warn the user via the annunciator.
        /// </summary>
        private void LoadDataGrid()
        {
            LaborDistributions laborDistribs = LaborDistributionsInstance;

            laborDistributionGrid.VirtualItemCount = pagerAboveDatagrid.RecordCount
                = pagerBelowDatagrid.RecordCount = laborDistribs.Count;

            int currentPageIndex = CurrentPageIndex;
            int pageCount = (pagerAboveDatagrid.RecordCount/laborDistributionGrid.PageSize) +
                (((pagerAboveDatagrid.RecordCount%laborDistributionGrid.PageSize) == 0) ? 0 : 1);
            pagerBelowDatagrid.PageCount = pagerAboveDatagrid.PageCount = pageCount;
            pagerBelowDatagrid.CurrentPage = pagerAboveDatagrid.CurrentPage = currentPageIndex + 1;

            laborDistributionGrid.DataSource = laborDistribs.GetLaborDistributionList
                (currentPageIndex*laborDistributionGrid.PageSize, laborDistributionGrid.PageSize);
            laborDistributionGrid.DataBind();

            laborDistributionGrid.Visible = pagerBelowDatagrid.Visible = pagerAboveDatagrid.Visible =
                (laborDistributionGrid.Items.Count > 0);

            if (pagerAboveDatagrid.Visible)
            {
                ManagePagination();
            }
            else
            {
                if (0 == LaborDistributionsInstance.Count)
                {
                    annunciator.Message = "No labor distribution data found for user.";
                }
            }
        }

       
        /// <summary>
        /// Manages the pagination logic.
        /// Set the First record and last record values for the pager controls
        /// based on the current page index and the data grid page size respectively
        /// </summary>
        private void ManagePagination()
        {
            int currentPageIndex = CurrentPageIndex;
            laborDistributionGrid.CurrentPageIndex = currentPageIndex;

            int startIndex = currentPageIndex*laborDistributionGrid.PageSize;

            pagerBelowDatagrid.FirstRecord = pagerAboveDatagrid.FirstRecord = startIndex + 1;
            pagerBelowDatagrid.LastRecord = pagerAboveDatagrid.LastRecord =
                Math.Min(startIndex + laborDistributionGrid.PageSize, laborDistributionGrid.VirtualItemCount);

            pagerBelowDatagrid.EnableFirstPage = pagerAboveDatagrid.EnableFirstPage =
                pagerBelowDatagrid.EnablePreviousPage = pagerAboveDatagrid.EnablePreviousPage =
                    (CurrentPageIndex != 0);

            pagerBelowDatagrid.EnableLastPage = pagerAboveDatagrid.EnableLastPage =
                pagerBelowDatagrid.EnableNextPage = pagerAboveDatagrid.EnableNextPage =
                    (CurrentPageIndex != (pagerAboveDatagrid.PageCount - 1));
        }

       

        /// <summary>
        /// Adds refresh dates currently visible on the page to the search criteria string
        /// to be passed down to reports. The criteria does not persist to the SearchCriteria
        /// object.
        /// </summary>
        /// <param name="searchCriteria">Object containing search criteria.</param>
        /// <returns>A string representation of search criteria. </returns>
        private string AddRefreshDatesToCriteria(SearchCriteria searchCriteria)
        {
            StringBuilder criteria = new StringBuilder(searchCriteria.ToString(";"));
            if (refreshDates.SalaryAsOfDateVisible)
            {
                criteria.AppendFormat("Last Salary Post|{0};", refreshDates.SalaryAsOfDate.ToShortDateString());
            }
            if (refreshDates.GLAsOfDateVisible)
            {
                criteria.AppendFormat("Last GL Post|{0};", refreshDates.GLPostAsOfDate.ToShortDateString());
            }
            if (refreshDates.POAPAsOfDateVisible)
            {
                criteria.AppendFormat("Last PO/AP Post|{0};", refreshDates.POAPAsOfDate.ToShortDateString());
            }
            return criteria.ToString();
        }

        /// <summary>
        /// Search the distribution data for the specified search criteria
        /// </summary>
        private void ProcessSearch()
        {
            LaborDistributionsInstance.
                Search(((CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString()));
            CurrentPageIndex = 0;
            LoadDataGrid();
          
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Handler for the event raised when the page is being initialized.
        /// Retrieve the cache policy and page cache policy in force.
        /// Deposit event handlers to support the datagrid pagination.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];

            InitializeComponent();
            base.OnInit(e);

            pagerAboveDatagrid.FirstPage += new CommandEventHandler(this.OnFirstPage);
            pagerAboveDatagrid.LastPage += new CommandEventHandler(this.OnLastPage);
            pagerAboveDatagrid.NextPage += new CommandEventHandler(this.OnNextPage);
            pagerAboveDatagrid.PreviousPage += new CommandEventHandler(this.OnPreviousPage);

            pagerBelowDatagrid.FirstPage += new CommandEventHandler(this.OnFirstPage);
            pagerBelowDatagrid.LastPage += new CommandEventHandler(this.OnLastPage);
            pagerBelowDatagrid.NextPage += new CommandEventHandler(this.OnNextPage);
            pagerBelowDatagrid.PreviousPage += new CommandEventHandler(this.OnPreviousPage);

        }

        /// <summary>
        /// Required method for Designer support 
        /// </summary>
        private void InitializeComponent()
        {
            this.insightHeader.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnHeaderNavigate);
            this.agreementsSubNavigation.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnSubNavigate);
            this.personnelSubNavigation.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnSubNavigation);
            this.agreementDetailsSubNavigation.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnAgrSubNavigation);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnBreadCrumbNavigate);
            this.laborDistributionGrid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemCreated);
            this.laborDistributionGrid.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.OnSort);
            this.laborDistributionGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemDataBound);
            
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        private void OnSubNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        private void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        private void OnSubNavigation(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        private void OnAgrSubNavigation(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        /// <summary>
        /// Invoked by the download bar when it catches an exception.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnDownloadFailed(object sender, CommandEventArgs e)
        {
            annunciator.Title = "Following error(s) occurred while downloading";
            annunciator.Message = Utility.ExceptionReport.GetExceptionInfo((Exception) e.CommandArgument, false);
        }

        public void PurgeCache()
        {
            ResultsCache.PurgeObject(cachePolicy);
        }
    }
}